<script type="text/javascript">
  var TableManaged = function () {
    return {
      //main function to initiate the module
      init: function () {
        $('#tableDataList').dataTable({
          "searching": true,
          "lengthChange": false,
          "pageLength": 15,
          "language": {
            "lengthMenu": "Display _MENU_ records",
            "paginate": {
              "previous": "<",
              "next": ">"
            },
            "info": "共_PAGES_页,_TOTAL_条",
            "infoFiltered": "",
            "infoEmpty":"共0页,0条",
            "zeroRecords": "没有找到符合条件的数据",
          }
        });
        $('#tableDataList_wrapper>div:first-child').css("display", "none");
      }
    };
  }();

  $(function () {
    $('.selectpicker').selectpicker({
      'selectedText': 'cat',
      'size': 8,
      'dropupAuto': false
    });
    TableManaged.init();
  });

  $('#modal-diagnosticResult').on('shown.bs.modal', function (e) {
    $('#modal-title').html('');
    $('#diagnosticResultCount').html('');
    $('#diagnosticResultTable').html('');

    var redisKey = $(e.relatedTarget).data('rediskey');
    var title = $(e.relatedTarget).data('title');
    $('#modal-title').html(title);
    $.get(
            '${request.contextPath}/manage/app/tool/diagnostic/data.json',
            {
              redisKey: redisKey,
              type: 7
            },
            function (data) {
              var diagnosticResultList = data.result;
              diagnosticResultList.forEach(function (diagnosticResult, index) {
                $('#diagnosticResultTable').append(
                        '<tr>' +
                        '<td>' + diagnosticResult + '</td>' +
                        '</tr>'
                );
              })
            }
    );

  });

  function changeAppId(selectElement, divElement, instanceElement, pwdElement) {
    var appId = $('#' + selectElement).selectpicker('val');
    if(appId != null && appId != ''){
      $('#' + divElement).css("display", "none");
      $('#'+ instanceElement).val('');
      $('#' + pwdElement).val('');
    }else{
      $('#' + divElement).css("display", "block");
    }
  }

  function submitDiagnostic() {
    var paramMap = new Map();
    var sourceAppId = $('#sample-source-select').selectpicker('val');
    var sourceInstances = $('#sourceInstances').val();
    var sourcePwd = $('#sourcePwd').val();
    if ((sourceAppId == null || sourceAppId == '') &&
      (sourceInstances == null || sourceInstances == '')) {
      alert("请选择或输入源应用");
      return;
    }

    if(sourceInstances != null && sourceInstances != ''){
      // 使用换行符分割字符串，得到一组server信息
      var hostPortArray = sourceInstances.split('\n');
      // 遍历主机信息数组，提取每个主机的IP地址
      if(hostPortArray.length > 0) {
          sourceInstances = hostPortArray[0];
       }
    }

    var targetAppId = $('#sample-target-select').selectpicker('val');
    var targetInstances = $('#targetInstances').val();
    var targetPwd = $('#targetPwd').val();
    if ((targetAppId == null || targetAppId == '') &&
      (targetInstances == null || targetInstances == '')) {
      alert("请选择或输入目标应用");
      return;
    }

    if(targetInstances != null && targetInstances != ''){
      // 使用换行符分割字符串，得到一组server信息
      var hostPortArray = targetInstances.split('\n');
      // 遍历主机信息数组，提取每个主机的IP地址
      if(hostPortArray.length > 0) {
          targetInstances = hostPortArray[0];
       }
    }

    paramMap.set("sourceAppId", sourceAppId);
    paramMap.set("sourceServers", sourceInstances);
    paramMap.set("sourcePwd", sourcePwd);
    paramMap.set("targetAppId", targetAppId);
    paramMap.set("targetServers", targetInstances);
    paramMap.set("targetPwd", targetPwd);
    paramMap.set("perCount", $('#scanCount').val());
    paramMap.set("totalCount", $('#totalCount').val());

    $.post(
            '${request.contextPath}/manage/app/tool/diagnostic/submit.json',
            {
              type: 7,
              params: mapToJson(paramMap)
            },
            function (data) {
              var status = data.status;
              if (status == 'success') {
                alert("检测任务提交成功，任务id：" + data.taskId);
                location.href = "${request.contextPath}/manage/app/tool/index?tabTag=sampleCompare";
              } else {
                toastr.error("检测任务提交失败,请查看系统日志确认相关原因!");
              }
            }
    );
  }

  function mapToJson(map) {
    var str = '{';
    var i = 1;
    for (var [key, value] of map.entries()) {
      if (i == map.size) {
        str += '"' + key + '":"'+ value + '"';
      }else{
        str += '"' + key + '":"'+ value + '",';
      }
      i++;
    }
    str += '}';
    return str;
  }

</script>

<div class="card">
  <div class="card-body">
    <div id="scan-div">
      <form class="row align-items-center" role="form" name="ec">
        <div class="row mb-2">
          <div class="col-md-4">
            <select id="sample-source-select" name="appId" class="selectpicker show-tick w-100 border rounded"
                    data-live-search="true" title="选择源应用"
                    onchange="changeAppId('sample-source-select', 'sourceDiv', 'sourceInstances', 'sourcePwd')">
              <option value="">选择源应用</option>
              <#list appDescMap?keys as key>
                <#assign appDesc = appDescMap?api.get(key)>
                <option value="${appDesc.appId!}" title="${appDesc.appId!} ${appDesc.name!}">
                  【${appDesc.appId!}】&nbsp;名称：${appDesc.name!}&nbsp;类型：${appDesc.typeDesc!}&nbsp;版本：${appDesc.versionName!}
                </option>
              </#list>
            </select>
          </div>
        </div>
        <div  id="sourceDiv" class="margin-top-10">
          <div class="row mb-2">
            <label for="sourceInstances" class="col-form-label col-auto">源应用节点</label>
            <div class="col-md-6">
              <textarea id="sourceInstances" type="text" class="form-control" name="sourceInstances"
                     placeholder="ip:port 多个实例换行分割"></textarea>
            </div>
            <label for="sourcePwd" class="col-form-label col-auto">源密码</label>
            <div class="col-md-3">
              <input id="sourcePwd" name="sourcePwd" type="text" class="form-control" placeholder="源redis密码">
            </div>
          </div>
        </div>

        <div class="row mb-2">
          <div class="col-md-4">
            <select id="sample-target-select" name="appId" class="selectpicker show-tick w-100 border rounded"
                    data-live-search="true" title="选择目标应用"
                    onchange="changeAppId('sample-target-select', 'targetDiv', 'targetInstances', 'targetPwd')">
              <option value="">选择目标应用</option>
              <#list appDescMap?keys as key>
              <#assign appDesc = appDescMap?api.get(key)>
              <option value="${appDesc.appId!}" title="${appDesc.appId!} ${appDesc.name!}">
                【${appDesc.appId!}】&nbsp;名称：${appDesc.name!}&nbsp;类型：${appDesc.typeDesc!}&nbsp;版本：${appDesc.versionName!}
              </option>
            </#list>
            </select>
          </div>
        </div>

        <div  id="targetDiv" class="margin-top-10">
          <div class="row mb-2">
            <label for="targetInstances" class="col-form-label col-auto">目标应用节点</label>
            <div class="col-md-6">
              <textarea id="targetInstances" type="text" class="form-control" name="targetInstances"
                        placeholder="ip:port 多个实例换行分割"></textarea>
            </div>
            <label for="targetPwd" class="col-form-label col-auto">目标密码</label>
            <div class="col-md-3">
              <input id="targetPwd" name="targetPwd" type="text" class="form-control" placeholder="目标redis密码">
            </div>
          </div>
        </div>

        <div class="row mb-2">
          <label for="scanCount" class="col-form-label col-auto">scan count</label>
          <div class="col-md-2">
            <input id="scanCount" name="scanCount" type="text" class="form-control" placeholder="每次批处理执行条数">
          </div>
          <label for="totalCount" class="col-form-label col-auto">total count</label>
          <div class="col-md-2">
            <input id="totalCount" name="totalCount" type="text" class="form-control" placeholder="每个节点处理总条数">
          </div>
          <div class="col-md-2">
              <button type="button" class="btn btn-success offset-md-1 col-auto" onclick="submitDiagnostic()">执行任务</button>
          </div>
        </div>
      </form>
    </div>
  </div>

  <div class="card-header">
    <h3 class="card-title">数据抽样比对列表</h3>
  </div>

  <div class="card-body">
    <div class="row">
      <div class="col-md-12">
        <div>
          <form class="row align-items-center" role="form" method="post" action="${request.contextPath}/manage/app/tool/index?tabTag=sampleCompare" id="appList" name="ec">
            <div class="col-md-2">
              <input type="text" class="form-control" id="appId" name="appId"
                     value="${appId!}" placeholder="应用id">
            </div>
            <div class="col-md-2">
              <input type="text" class="form-control" id="parentTaskId" name="parentTaskId"
                     value="${parentTaskId!}" placeholder="任务id">
            </div>
            <div class="col-md-2">
              <input type="text" class="form-control" id="auditId" name="auditId"
                     value="${auditId!}" placeholder="审批id">
            </div>
            <button type="submit" class="btn btn-success col-auto">查询</button>
          </form>
        </div>
      </div>
    </div>
    <br/>
    <div class="row">
      <div class="col-md-12">
        <div class="portlet box light-grey table-responsive" id="sampleCompareIndex">

          <table class="table table-striped table-bordered table-hover" id="tableDataList" style="white-space: nowrap">
            <thead>
            <tr>
              <td>序号</td>
              <th>任务id</th>
              <th>审批id</th>
              <th>抽样信息</th>
              <th>创建时间</th>
              <th>诊断状态</th>
              <th>诊断耗时</th>
              <th>诊断结果</th>
            </tr>
            </thead>
            <tbody>
            <#list diagnosticTaskRecordList as record>
              <#assign app_id = record.appId>
              <tr>
                <td>${record_index + 1}</td>
                <td>
                  <a target="_blank" href="${request.contextPath}/manage/task/flow?taskId=${record.taskId!}">
                    ${record.taskId!}
                  </a>
                </td>
                <td>
                    <a target="_blank"
                       href="${request.contextPath}/manage/app/auditList?auditId=${record.auditId!}">
                      ${record.auditId!}
                    </a>
                </td>
                <td width="20%" style="word-wrap:break-word;word-break:break-all;">
                  ${record.diagnosticCondition!}
                </td>
                <td>
                  ${record.createTime!?string("yyyy-MM-dd HH:mm:ss")}
                </td>
                <td>
                  <#if (record.status==0)>诊断中</#if>
                  <#if (record.status==1)>诊断完成</#if>
                  <#if (record.status==2)>诊断异常</#if>
                </td>
                <td>
                  <#if (record.status==1)>${record.formatCostTime!}</#if>
                </td>
                <td>
                  <#if (record.status==0) || (record.status==1)>
                    <a target="_blank"
                       href="${request.contextPath}/manage/app/tool//diagnostic/sampleCompareData?redisKey=${record.redisKey!}">
                      查看结果
                    </a>
                    <!--<button type="button" class="btn btn-sm btn-info"
                            data-bs-target="#modal-diagnosticResult" data-bs-toggle="modal"
                            data-rediskey="${record.redisKey!}"
                            data-title="数据抽样对比">
                      查看结果
                    </button>-->
                  </#if>
                </td>
              </tr>
            </#list>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<div id="modal-diagnosticResult" class="modal fade" tabindex="-1">
  <div class="modal-dialog" style="width: 100%">
    <div class="modal-content">

      <div class="modal-header">
        <h4 class="modal-title">
          诊断结果
          <small><label id="modal-title" style="color: #00BE67"></label></small>
        </h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-hidden="true"></button>
      </div>

      <form class="form-horizontal form-bordered form-row-stripped">
        <div class="modal-body" style="height:500px; overflow:scroll;">
          <div class="row">
            <!-- 控件开始 -->
            <div class="col-md-12">
              <table class="table table-bordered table-striped table-hover">
                <thead id="diagnosticResultCount"></thead>
                <tbody id="diagnosticResultTable"></tbody>
              </table>
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button type="button" data-bs-dismiss="modal" class="btn btn-secondary">Close</button>
        </div>
      </form>
    </div>
  </div>
</div>
